import { Request, RequestModel } from '../models/request.model';

/**
 * 存储键枚举
 */
export enum StorageKey {
  HISTORY = 'webpost_history',
  SAVED = 'webpost_saved',
  SETTINGS = 'webpost_settings'
}

/**
 * 存储服务类
 * 负责处理插件的存储需求
 */
export class StorageService {
  /**
   * 获取历史请求
   * @returns 历史请求数组Promise
   */
  static async getHistory(): Promise<Request[]> {
    try {
      const result = await chrome.storage.local.get(StorageKey.HISTORY);
      const historyData = result[StorageKey.HISTORY] || '[]';
      const historyItems: RequestModel[] = JSON.parse(historyData);
      return historyItems.map(item => new Request(item));
    } catch (error) {
      console.error('Error getting history:', error);
      return [];
    }
  }

  /**
   * 保存请求到历史记录
   * @param request 请求对象
   * @param maxSize 最大历史记录数量
   */
  static async saveToHistory(request: Request, maxSize: number = 50): Promise<void> {
    try {
      const history = await this.getHistory();
      
      // 添加到历史记录的开头
      history.unshift(request);
      
      // 限制历史记录大小
      while (history.length > maxSize) {
        history.pop();
      }
      
      // 序列化并保存
      const serializedHistory = JSON.stringify(history);
      await chrome.storage.local.set({
        [StorageKey.HISTORY]: serializedHistory
      });
    } catch (error) {
      console.error('Error saving to history:', error);
    }
  }

  /**
   * 清除历史记录
   */
  static async clearHistory(): Promise<void> {
    try {
      await chrome.storage.local.set({
        [StorageKey.HISTORY]: '[]'
      });
    } catch (error) {
      console.error('Error clearing history:', error);
    }
  }

  /**
   * 获取保存的请求
   * @returns 保存的请求数组Promise
   */
  static async getSavedRequests(): Promise<Request[]> {
    try {
      const result = await chrome.storage.local.get(StorageKey.SAVED);
      const savedData = result[StorageKey.SAVED] || '[]';
      const savedItems: RequestModel[] = JSON.parse(savedData);
      return savedItems.map(item => new Request(item));
    } catch (error) {
      console.error('Error getting saved requests:', error);
      return [];
    }
  }

  /**
   * 保存请求
   * @param request 请求对象
   */
  static async saveRequest(request: Request): Promise<void> {
    try {
      // 确保请求有名称
      if (!request.name || request.name.trim() === '') {
        request.name = `${request.method} ${request.url}`;
      }
      
      const savedRequests = await this.getSavedRequests();
      
      // 检查是否已存在相同ID的请求
      const existingIndex = savedRequests.findIndex(r => r.id === request.id);
      if (existingIndex >= 0) {
        // 更新现有请求
        savedRequests[existingIndex] = request;
      } else {
        // 添加新请求
        savedRequests.push(request);
      }
      
      // 序列化并保存
      const serializedRequests = JSON.stringify(savedRequests);
      await chrome.storage.local.set({
        [StorageKey.SAVED]: serializedRequests
      });
    } catch (error) {
      console.error('Error saving request:', error);
    }
  }

  /**
   * 删除保存的请求
   * @param requestId 请求ID
   */
  static async deleteSavedRequest(requestId: string): Promise<void> {
    try {
      const savedRequests = await this.getSavedRequests();
      const filteredRequests = savedRequests.filter(r => r.id !== requestId);
      
      // 序列化并保存
      const serializedRequests = JSON.stringify(filteredRequests);
      await chrome.storage.local.set({
        [StorageKey.SAVED]: serializedRequests
      });
    } catch (error) {
      console.error('Error deleting saved request:', error);
    }
  }

  /**
   * 获取设置
   * @returns 设置对象
   */
  static async getSettings<T>(defaultSettings: T): Promise<T> {
    try {
      const result = await chrome.storage.local.get(StorageKey.SETTINGS);
      const settingsData = result[StorageKey.SETTINGS];
      return settingsData ? JSON.parse(settingsData) : defaultSettings;
    } catch (error) {
      console.error('Error getting settings:', error);
      return defaultSettings;
    }
  }

  /**
   * 保存设置
   * @param settings 设置对象
   */
  static async saveSettings<T>(settings: T): Promise<void> {
    try {
      await chrome.storage.local.set({
        [StorageKey.SETTINGS]: JSON.stringify(settings)
      });
    } catch (error) {
      console.error('Error saving settings:', error);
    }
  }
} 